package com.xuxueli.applyModules.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description 分布式锁
 **/
@Component
public class RedisLockUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取分布式锁
     *
     * @param key key值
     * @return 是否获取到
     */
    public boolean tryLock(String key, Long expire) {
        String lock = "try_lockkey" + key;
        return (boolean) redisTemplate.execute((RedisCallback) connection -> {
            long curMills = System.currentTimeMillis();
            long expireAt = curMills + expire + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
            if (acquire) {
                return true;
            } else {
                byte[] value = connection.get(lock.getBytes());
                if (Objects.nonNull(value) && value.length > 0) {
                    long expireTime = Long.parseLong(new String(value));
                    // 如果锁已经过期
                    if (expireTime < curMills) {
                        // 重新加锁，防止死锁
                        byte[] oldValue = connection.getSet(lock.getBytes(),
                            String.valueOf(curMills + expire + 1).getBytes());
                        return Long.parseLong(new String(oldValue)) < curMills;
                    }
                }
            }
            return false;
        });
    }

    /**
     * 删除锁
     */
    public void releaseLock(String key) {
        redisTemplate.delete("try_lockkey" + key);
    }

}
